<!-- 头部横向导航栏 -->
<template>
  <div >
    <ScrollPane ref="scrollPane" class="q-pa-xs no-wrap text-subtitle2" >
      <router-link
        v-for="tag in visitedViews"
        :key="tag.path"
        :class="isActive(tag)?'active':''"
        :to="{ path: tag.path, query: tag.query, fullPath: tag.fullPath }"
        tag="span"
        class="tags-view-item"
        @contextmenu.prevent="openMenu(tag,$event)"
        ref="tag"
      >
        <span class="q-px-sm">{{ tag.title }}</span>
        <q-icon class="q-pr-sm" name="close" v-if="isAffix(tag)" @click.prevent.stop="closeSelectedTag(tag)"></q-icon>
      </router-link>
    </ScrollPane>
    <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">刷新</li>
      <li v-if="isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">关闭</li>
      <li @click="closeOthersTags">关闭其他</li>
      <li @click="closeAllTags(selectedTag)">关闭所有</li>
    </ul>
  </div>
</template>

<script>
import ScrollPane from './ScrollPane'
import { mapGetters } from 'vuex'
import { routes } from '../../router/routes.js'
export default {
  data () {
    return {
      visible: false,
      top: 0,
      left: 0,
      selectedTag: {},
      affixTags: [],
      tagElement: []
    };
  },

  components: {
    ScrollPane
  },

  computed: {
    ...mapGetters(['visitedViews'])
  },
  watch: {
    $route(val) {
      if (val) {
        this.addTags()
        this.moveToCurrentTag()
      }
    },
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    },
  },

  mounted() {
    this.initTags()
    this.addTags()
  },

  methods: {
    // 是否激活
    isActive(route) {
      return route.path === this.$route.path
    },
    // 是否固定在头部
    isAffix(tag) {
      return tag.meta && tag.meta.affix
    },
    // 整理路由
    filterAffixTags(routes, basePath = '/') {
      // const path = require("path")
      let tags = []
      if (routes && routes.length > 0) {
        let _route = routes.find(route => route.meta.affix)
        const tagPath = _route.children[0].path
        const _name = _route.children[0].name
        const _meta = _route.children[0].meta
        tags.push({
          fullPath: tagPath,
          path: tagPath,
          name: _name,
          meta: { ..._meta }
        })
      }
      // routes.forEach((route, index) => {
          // if (index === 0 && route.children) {
          //   const tagPath = route.children[0].path
          //   const _name = route.children[0].name
          //   const _meta = route.children[0].meta
          //   tags.push({
          //     fullPath: tagPath,
          //     path: tagPath,
          //     name: _name,
          //     meta: { ..._meta }
          //   })
          // }
      //     // if (route.children) {
      //     //   const tempTags = this.filterAffixTags(route.children, route.path)
      //     //   if (tempTags.length >= 1) {
      //     //     tags = [...tags, ...tempTags]
      //     //   }
      //     // }
      // })
      return tags
    },
    // 初始化加载tab
    initTags() {
      const affixTags = this.affixTags = this.filterAffixTags(routes)
      if (affixTags[0].path === '/') return
      for (const tag of affixTags) {
        // Must have tag name
        if (tag.name) {
          this.$store.dispatch('app/addVisitedView', tag)
        }
      }
    },
    // 添加tags
    addTags() {
      const { name } = this.$route
      if (name) {
        this.$store.dispatch('app/addView', this.$route)
      }
    },
    // 是否关闭
    closeSelectedTag(view) {
      this.$store.dispatch('app/delView', view).then(({ visitedViews }) => {
        if (this.isActive(view)) {
          this.toLastView(visitedViews, view)
        }
      })
    },
    // 刷新
    refreshSelectedTag(view) {
      this.$store.dispatch('app/delCachedView', view).then(() => {
        const { path } = view
        this.$nextTick(() => {
          this.$router.replace({ path: path })
        })
      })
    },
    // 关闭其他
    closeOthersTags() {
      this.$router.push(this.selectedTag)
      this.$store
        .dispatch('app/delOthersViews', this.selectedTag)
        // .then(() => {
        //   this.moveToCurrentTag()
        // })
    },
    // 关闭所有
    closeAllTags(selectedTag) {
      this.$store.dispatch('app/delAllVisitedViews').then(res => {
        if (this.affixTags.some(tag => tag.path === selectedTag.path)) {
          this.$router.replace({ path: selectedTag.path })
          return
        }
        const latestView = res.slice(-1)[0]
        if (latestView) {
          this.$router.replace({ path: latestView.path })
        } else {
          this.$router.replace({ path: selectedTag.path })
        }

      })
    },
    // 移动到当前tag
    moveToCurrentTag() {
      if (!this.$refs.tag) return
      this.$nextTick(() => {
        const tags = this.$refs.tag.$el
        const tagEle = document.getElementsByClassName('tags-view-item')
        if (this.$refs.scrollPane) this.$refs.scrollPane.moveToTarget(tags, this.$route.path, this.visitedViews, tagEle)
      })
    },
    // 获取删除之后的最后一个tab并重定向到它
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push(latestView.fullPath)
      } else {
        if (view.name === 'Dashboard') { // RealTimeState 如果删除的是首页，还重定向到首页
          this.$router.replace({ path: '/' + view.fullPath })
        } else {
          this.$router.push('/a')
        }
      }
    },
    // 打开右侧菜单
    openMenu(tag, e) {
      const menuMinWidth = 105
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft + 16 // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = e.clientY + 30
      this.visible = true
      this.selectedTag = tag

    },
    // 关闭菜单
    closeMenu() {
      this.visible = false
    },
  }
}

</script>
<style lang='scss' scoped>
// 去掉下划线
a {
  text-decoration: none;
}
.router-link-active {
  text-decoration: none;
}
.tags-view-item {
  display: inline-block;
  height: 38px;
  color: #1c1c1c;
  margin-right: 16px;
}
.active {
  background-color: #f0f2f5;
  border-top: 2px solid var(--q-accent);
}
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;
    &:hover {
      background: #eee;
      color: $primary;
    }
  }
}
</style>
